package keytool;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import cn.com.jit.ida.util.pki.Parser;
import cn.com.jit.ida.util.pki.cert.X509Cert;
import cn.com.jit.ida.util.pki.cipher.JKey;
import cn.com.jit.ida.util.pki.pkcs.PKCS12;

public class PfxToJKS {
	
	public void genKeyStore() {
		try {
			String pfxPath = getUserInput("pls input pfx file path:");
			String pfxPwd = getUserInput("pls input pfx password:");
			String keystorePath = getUserInput("pls input keystore file path (to be create):");
			String keystorePwd = getUserInput("pls input keystore password:");
			
			PKCS12 p12 = new PKCS12();
			
			p12.load(pfxPath);
			p12.decrypt(pfxPwd.toCharArray());
			
			JKey prvKey = p12.getPrivateKey();
			X509Cert userCert = p12.getCertificate();			
			X509Cert[] allCerts = p12.getCerts();
			
			List rootCertsList = new ArrayList<X509Cert>();
			for(X509Cert cert : allCerts) {
				if(!cert.getSubject().equals(userCert.getSubject())) {
					rootCertsList.add(cert);
				}
			}
			X509Cert[] rootCerts = new X509Cert[rootCertsList.size()];
			rootCertsList.toArray(rootCerts);						
			
			Key javaPrvKey = Parser.convertKey(prvKey);
			Certificate javaUserCert = convertCertificate(userCert);
			Certificate[] javaRootCerts = new Certificate[rootCerts.length];
			for(int i = 0; i < rootCerts.length; i++) {
				javaRootCerts[i] = convertCertificate(rootCerts[i]);
			}						
			
			KeyStore keyStore = KeyStore.getInstance("JKS");
		    keyStore.load(null, null);
		    
		    keyStore.setKeyEntry(userCert.getSubject(), javaPrvKey, keystorePwd.toCharArray(), new Certificate[]{javaUserCert});
		    for(X509Cert cert : rootCerts) {
		    	keyStore.setCertificateEntry(cert.getSubject(), convertCertificate(cert));
		    }
		    
		    FileOutputStream fous = new FileOutputStream(keystorePath);
		    keyStore.store(fous, keystorePwd.toCharArray());
		    fous.flush();
		    fous.close();
		    
		    System.out.println("generate keystore file SUCCESS");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private String getUserInput(String message) {
		System.out.print(message);
		Scanner scanner = new Scanner(System.in);
		String input = scanner.nextLine();
		return input;
	}
	
	private Certificate convertCertificate(X509Cert cert) throws Exception {
		ByteArrayInputStream bis = new ByteArrayInputStream(cert.getEncoded());
		
		CertificateFactory certFac = CertificateFactory.getInstance("X.509");
		Certificate javaCert = certFac.generateCertificate(bis);
		
		return javaCert;
	}
	
	public static void main(String[] args) {
		PfxToJKS kst = new PfxToJKS();
		kst.genKeyStore();
	}

}
